//
//  MainViewController.swift
//  Weibo8023
//
//  Created by styshy on 15/12/6.
//  Copyright © 2015年 sz. All rights reserved.
//

import UIKit

class MainViewController: UITabBarController {
    
    
    @objc private func clickComposedButton(){
        print("点击了撰写按钮")
        let composeVc = ComposeViewController()
        let navi = UINavigationController(rootViewController: composeVc)
        presentViewController(navi, animated: true, completion: nil)
    }

    override func viewDidLoad() {
        super.viewDidLoad()

        // Do any additional setup after loading the view.
        // 添加子控制器
        self.addChildViewControllers()
        
        // 添加撰写按钮
        self.setUpComponentBtn()
    }
    
    override func viewWillAppear(animated: Bool) {
        super.viewWillAppear(animated)
        
        tabBar.bringSubviewToFront(composedBtn)
//
//        // 或者在这个位置添加撰写按钮也可以
//        self.setUpComponentBtn()

    }
    
    // MARK: - 懒加载撰写按钮
    private lazy var composedBtn:UIButton = UIButton(imageName: "tabbar_compose_icon_add", backImageName: "tabbar_compose_button")
    
}

extension MainViewController{
    
    private func setUpComponentBtn(){
        tabBar.addSubview(composedBtn)
        
        let count:Int = childViewControllers.count
        
        // 让按钮宽一点点，能够解决手指触摸的容错问题
        let w:CGFloat = view.bounds.width/CGFloat(count) - 1
        
        composedBtn.frame = CGRectInset(tabBar.bounds, 2 * w, 0)
        
        // 给按钮添加事件
        composedBtn.addTarget(self, action: "clickComposedButton", forControlEvents: UIControlEvents.TouchUpInside)
    }
    
     // 添加所有子控制器
     private func addChildViewControllers(){
        
        // 在AppDelegate中已经设置过渲染样式，可以注释掉
//        tabBar.tintColor = UIColor.orangeColor()
        
        addChildViewController(HomeTableViewController(), title: "首页", imageNamed: "tabbar_home")
        addChildViewController(MessageTableViewController(), title: "消息", imageNamed: "tabbar_message_center")
        
        // 添加撰写按钮
        addChildViewController(UIViewController())
        
        addChildViewController(DiscoverTableViewController(), title: "发现", imageNamed: "tabbar_discover")
        addChildViewController(ProfileTableViewController(), title: "我", imageNamed: "tabbar_profile")
    
     }
    
    /// 创建控制器
    ///
    /// - parameter vc:         控制器
    /// - parameter title:      名称
    /// - parameter imageNamed: 图片
    private func addChildViewController(vc:UIViewController, title:String, imageNamed:String){
        
        let navi:UINavigationController = UINavigationController(rootViewController: vc)
        
        vc.title = title
        vc.tabBarItem.image = UIImage(named: imageNamed)
        
        addChildViewController(navi)
    }
}
